﻿using ReaderB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.InterfaceServer;

namespace ZK.HardWareHelp
{
    /// <summary>
    /// 明华室外读卡器（网口）
    /// </summary>
    public class MW_102N_CardReader
    {
        private byte fComAdr = 0xff; //当前操作的ComAdr
        private int frmcomportindex;
        private byte[] fPassWord = new byte[4];
        private byte MaskLen;
        private byte MaskFlag;
        private byte Maskadr;
        private int ferrorcode;
        public string Ip { get; set; }
        public int Port { get; set; }

        private System.Timers.Timer timer = new System.Timers.Timer(Convert.ToDouble(Common.AppConfigHelper.GetAppSettings("CardReaderTime"))); //设置时间间隔为5秒
        public MW_102N_CardReader(string ip, int port)
        {
            //timer.Interval = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("CardReaderTime"));
            //timer.Enabled = true;
            //timer.Tick += new EventHandler(timer1EventProcessor);//添加事件
            InitTimer(ip, port);
            OpenRes();
        }

        private void InitTimer(string ip, int port)
        {
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer1EventProcessor);
            timer.AutoReset = false; //
            timer.Enabled = true;
            timer.Start();
            this.Ip = ip;
            this.Port = port;
            // OpenRes();
        }

        public MW_102N_CardReader(string mark)
        {
            Common.Log4.LogManage.WriteInfo("MW_102N_CardReader构造函数的参数是 " + mark);
            try
            {
                if (mark == "MW")
                {
                    Common.HaredWareCommonM cardReader = Common.IConfig.GetSetCardReaderMW;
                    TestConnect.CheckDeviceStatus(cardReader.Ip, cardReader.Name);
                    //timer.Elapsed += new System.Timers.ElapsedEventHandler(timer1EventProcessor);
                    //timer.AutoReset = true; //
                    //timer.Enabled = true;
                    //timer.Start();
                    //this.Ip = cardReader.Ip;
                    //this.Port = Convert.ToInt32(cardReader.Port);

                    InitTimer(cardReader.Ip, Convert.ToInt32(cardReader.Port));
                    OpenRes();
                }
                if (mark == "DC")
                {
                    Common.HaredWareCommonM cardReader = Common.IConfig.GetSetCardReaderDC;
                    TestConnect.CheckDeviceStatus(cardReader.Ip, cardReader.Name);
                    //timer.Elapsed += new System.Timers.ElapsedEventHandler(timer1EventProcessor);
                    //timer.AutoReset = true; //
                    //timer.Enabled = true;
                    //timer.Start();
                    //this.Ip = cardReader.Ip;
                    //this.Port = Convert.ToInt32(cardReader.Port);
                    InitTimer(cardReader.Ip, Convert.ToInt32(cardReader.Port));
                    OpenRes();
                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteInfo("室外读卡器初始化带标记 " + ex.ToString());
            }

        }

        public MW_102N_CardReader()
        {
            Common.HaredWareCommonM cardReader = Common.IConfig.GetSetCardReader;
            TestConnect.CheckDeviceStatus(cardReader.Ip, cardReader.Name);
            //timer.Elapsed += new System.Timers.ElapsedEventHandler(timer1EventProcessor);
            //timer.AutoReset = true; //
            //timer.Enabled = true;
            //timer.Start();
            //this.Ip = cardReader.Ip;
            //this.Port = Convert.ToInt32(cardReader.Port);
            InitTimer(cardReader.Ip, Convert.ToInt32(cardReader.Port));
            OpenRes();
        }

        private void timer1EventProcessor(object sender, EventArgs e)
        {
            Common.Log4.LogManage.WriteInfo("初始化 timer1EventProcessor 定时器");
            Inventory();
        }
        public void WriteCard(string oldStr, string newStr)
        {
            int? res;
            byte WordPtr, ENum;
            byte Mem = 1;//保留区0 epc1 tid2 用户区3 
            string s2;
            byte WNum = 0;
            byte Writedatalen = 6;
            ENum = Convert.ToByte(oldStr.Length / 4);
            byte[] EPC = new byte[ENum];
            EPC = HexStringToByteArray(oldStr);
            s2 = newStr;
            WNum = Convert.ToByte(s2.Length / 4);
            byte[] Writedata = new byte[WNum * 2];
            Writedata = HexStringToByteArray(s2);
            WordPtr = Convert.ToByte("2", 16);
            fPassWord = HexStringToByteArray("00000000");
            Maskadr = Convert.ToByte("00", 16);
            MaskLen = Convert.ToByte("00", 16);
            MaskFlag = 0;
            int WrittenDataNum = 0;
            byte EPClength = 0;
            EPClength = Convert.ToByte(ENum * 2);

            timer.Stop();
            res = StaticClassReaderB.WriteCard_G2(
                ref fComAdr,
                EPC,
                Mem,
                WordPtr,
                Writedatalen,
                Writedata,
                fPassWord,
                Maskadr,
                MaskLen,
                MaskFlag,
                WrittenDataNum,
                EPClength,
                ref ferrorcode,
                frmcomportindex
                );
            if (res != 0)
            {
                Common.Log4.LogManage.WriteErr("mw-102n读卡器写卡失败 " + nameof(this.Ip) + ":" + this.Ip + "," + nameof(this.Port) + ":" + this.Port + "错误代码" + res);
                // Common.MessageDialog.MessageBoxShow("mw-102n读卡器写卡失败，原因未知", "mw-102n读卡器");
            }
            timer.Start();
        }
        public void OpenRes()
        {
            try
            {
                int res = 1;
                Task.Factory.StartNew(() =>
                {
                    res = StaticClassReaderB.OpenNetPort(this.Port, this.Ip, ref fComAdr, ref frmcomportindex);
                }).Wait(3000);

                if (res != 0)
                {
                    timer.Stop();
                    timer.Dispose();
                    Common.Log4.LogManage.WriteErr("OpenRes mw-102n读卡器打开失败 " + nameof(this.Ip) + ":" + this.Ip + "," + nameof(this.Port) + ":" + this.Port + "错误代码" + res);
                    // Common.MessageDialog.MessageBoxShow("mw-102n读卡器打开失败，原因未知", "mw-102n读卡器");
                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr("mw-102n读卡器打开失败 " + nameof(this.Ip) + ":" + this.Ip + "," + nameof(this.Port) + ":" + this.Port + "错误代码" + ex.ToString());
                //Common.MessageDialog.MessageBoxShow("mw-102n读卡器打开失败 ");
                Common.DelegateHelper.InfoMessageEvent?.Invoke("室外读卡器打开失败！");
            }
        }

        public void CloseRes()
        {
            int res;
            timer.Stop();
            timer.Dispose();
            res = StaticClassReaderB.CloseNetPort(frmcomportindex);
            if (res != 0)
            {
                Common.Log4.LogManage.WriteErr("mw-102n读卡器关闭失败 " + nameof(this.Ip) + ":" + this.Ip + "," + nameof(this.Port) + ":" + this.Port + "错误代码" + res);
                // Common.MessageDialog.MessageBoxShow("mw-102n读卡器关闭失败，原因未知", "mw-102n读卡器");
            }

        }
        private void Inventory()
        {
            try
            {
                Common.Log4.LogManage.WriteInfo(" Inventory begain");
                int CardNum = 0;
                int Totallen = 0;
                byte[] EPC = new byte[5000];
                string temps;
                byte AdrTID = 0;
                byte LenTID = 0;
                byte TIDFlag = 0;
                int? res;
                ListViewItem aListItem = new ListViewItem();
                res = StaticClassReaderB.Inventory_G2(ref fComAdr, AdrTID, LenTID, TIDFlag, EPC, ref Totallen, ref CardNum, frmcomportindex);
                if ((res == 1) | (res == 2) | (res == 3) | (res == 4) | (res == 0xFB))//代表已查找结束，
                {
                    byte[] daw = new byte[Totallen];
                    Array.Copy(EPC, daw, Totallen);
                    temps = ByteArrayToHexString(daw);
                    if (!string.IsNullOrEmpty(temps))
                    {
                        Common.Log4.LogManage.WriteInfo("初始化 " + temps.Substring(2));
                        Common.DelegateHelper.MW_102N_MessageReceivedEvent?.Invoke(temps.Substring(2));
                    }
                }
                timer.Start();
            }
            catch (Exception ex)
            {
                Common.DelegateHelper.InfoMessageEvent?.Invoke("室外读卡器执行Inventory异常");
                Common.Log4.LogManage.WriteInfo("室外读卡器执行Inventory异常 信息：" + ex.ToString());
            }
        }
        private string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
            return sb.ToString().ToUpper();

        }
        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

    }
}
